﻿#include "ReleaseNotesModelParser.h"

ReleaseNotesModelParser::ReleaseNotesModelParser()
    : IModelParser<ReleaseNotesModel>()
{

}

QString ReleaseNotesModelParser::toString(const ReleaseNotesModel &model)
{
    QJsonObject root;

    QJsonArray notes;
    for (const auto& note : model.notes) {
        notes.append(noteToJson(note));
    }

    root["notes"] = notes;

    setLastError("");
    // 创建 JSON 文档并转换为字符串
    QJsonDocument doc(root);
    return doc.toJson(QJsonDocument::Indented);
}

ReleaseNotesModel ReleaseNotesModelParser::parseFromJson(const QJsonObject &json)
{
    ReleaseNotesModel releaseNotes;

    QJsonArray notes = json["notes"].toArray();
    for (const auto& note : notes) {
        releaseNotes.notes.append(parseNote(note.toObject()));
    }

    setLastError("");
    return releaseNotes;
}

NoteModel ReleaseNotesModelParser::parseNote(const QJsonObject &json)
{
    NoteModel note;
    note.title = json["title"].toString();
    note.version = json["version"].toInt();
    note.date = json["date"].toString();

    QJsonArray changes = json["changes"].toArray();
    for (const auto& change : changes) {
        note.changes.append(change.toString());
    }

    return note;
}

QJsonObject ReleaseNotesModelParser::noteToJson(const NoteModel &note)
{
    QJsonObject noteObj;

    noteObj["title"] = note.title;
    noteObj["version"] = note.version;
    noteObj["date"] = note.date;

    // 添加 变更点 数组
    QJsonArray changes;
    for (const QString& change : note.changes) {
        changes.append(change);
    }
    noteObj["changes"] = changes;

    return noteObj;
}
